package com.wx.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 七牛云文件上传下载
 */
public class QiNiuFileUpload {
    private static String accesskey;
    private static String secretkey;
    private static String bucket;


    // 加载配置文件
    static {
        Properties properties = new Properties();
        Class<?> aClass = null;
        try {
            aClass = Class.forName("com.wx.utils.QiNiuFileUpload");
            InputStream resourceAsStream = aClass.getResourceAsStream("/qiniu.properties");
            properties.load(resourceAsStream);
            accesskey = properties.getProperty("accesskey");
            secretkey = properties.getProperty("secretkey");
            bucket = properties.getProperty("bucket");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 文件传到七牛云
     *
     * @param bytes    需要上传文件的二进制数组
     * @param fileName 上传的文件名
     * @throws QiniuException
     */
    public static void fileupload(byte[] bytes, String fileName) throws QiniuException {
        // 配置时区
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager  uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accesskey, secretkey);
        String uploadToken = auth.uploadToken(bucket);
        // 文件上传
        Response response = uploadManager.put(bytes, fileName, uploadToken);
    }
    /**
     * 文件删除
     */
    public static void deleteFile(String name) throws QiniuException {

        Configuration cfg = new Configuration(Zone.zone2());
        Auth auth = Auth.create(accesskey, secretkey);
        BucketManager manager = new BucketManager(auth, cfg);
        manager.delete(bucket,name);
    }
}
